<!-- 
  对echart进行封装，只需要传入option即可。
  对option进行监听，图表根据数据动态变化。
 -->
<template>
  <div class="echart" />
</template>

<script>
import echarts from 'echarts'
import { debounce } from '@/utils'
import { watch, onMounted, onBeforeUnmount } from 'vue'
export default {
  name: 'v-chart',
  props: {
    // 配置项
    option: {
      type: Object,
      default: () => ({})
    },
  },
  setup(props) {
    let chart = null
    function initChart() {
      let dom = document.querySelector('.echart')
      chart = echarts.init(dom)
      setOption()
    }
    function setOption() {
      props.option && chart.setOption(props.option, 6000)
    }
    onMounted(() => {
      initChart()
    })
    const resizeHandler = debounce(() => {
      chart && chart.resize()
    }, 100)
    window.addEventListener('resize', resizeHandler)
    watch(
      () => props.option,
      () => setOption(),
      { deep: true }
    )
    onBeforeUnmount(() => {
      if (chart) {
        window.removeEventListener('resize', resizeHandler)
        chart.dispose()
        chart = null
      }
    })
  }
}
</script>

<style lang="less" scoped>
.echart {
  width: 600px;
  height: 400px;
}
</style>
